<?php
include_once '../include/lxbase.class.php';
if(!empty($_GET["code"])){
	$webconn=new Lxbase();
	$code=$_GET["code"];
	$state=$_GET["state"];
	if(empty($state)){die("微信授权失败");}
	$data = json_decode(base64_decode($state),true);
	$u=$data["u"];
	$mid=$data["mid"];
	$minfo = $webconn->mongo()->findOne('wxtemp',array("_id"=>new MongoId("$mid")));
	$url=$minfo["content"];
	$wxinfo = $webconn->viewdata("*","wxuser","where userid={$u}");
	$json=$webconn->call_get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".trim($wxinfo["appid"])."&secret=".trim($wxinfo["secret"])."&code={$code}&grant_type=authorization_code");
	$userinfo=json_decode($json,true);
	$openid=$userinfo["openid"];
	if(empty($openid)){print_r($userinfo);die("未获取到openid");}
	$token=$userinfo["access_token"];
	$rtoken=$userinfo["refresh_token"];
	$temurl="https://api.weixin.qq.com/sns/userinfo?access_token={$token}&openid={$openid}&lang=zh_CN";
	$getuinfo=json_decode($webconn->call_get($temurl),true);
	if(!empty($getuinfo["nickname"])){
		$uname=preg_replace('/[\x{10000}-\x{10FFFF}]/u', '',$getuinfo["nickname"]);
		$uface=$getuinfo["headimgurl"];
		$city=$getuinfo["city"];
		$province=$getuinfo["province"];
		$sex=$getuinfo["sex"];
	}else{
		$uname='';
		$uface='';
	}
	$tokentim=time()+7200;
	$t=$webconn->oncedata("token","users","where id={$u}");
	$checkinfo=$webconn->viewdata("id","wxguest","where openid='".$openid."'");
	if($sex==1){
		$sexname='男';	
	}elseif($sex==2){
		$sexname='女';
	}else{
		$sexname='未知';
	}
	if(empty($checkinfo)){
		$into="openid='{$openid}',uid='".$t."',uname='{$uname}',uface='{$uface}',province='{$province}',city='{$city}',sex='{$sexname}',token='{$token}',rtoken='{$rtoken}',userid={$u},tokentim='{$tokentim}'";
		$webconn->setdata("wxguest",$into);
	}else{
		$into="uname='{$uname}',uface='{$uface}',province='{$province}',city='{$city}',sex='{$sexname}',token='{$token}',rtoken='{$rtoken}',tokentim='{$tokentim}'";
		$webconn->updata("wxguest",$into,"where id={$checkinfo['id']}");
	}
	$backdata["openid"]=$openid;
	if(!empty($uname)){
	$backdata["uname"]=$uname;
	$backdata["uface"]=$uface;
	$backdata["province"]=$province;
	$backdata["city"]=$city;
	$backdata["sex"]=$sex;
	}
	$bdata=base64_encode(serialize($backdata));
	if(strpos($url,'?') === false){
		$url=$url."?u=".$u."&openid=".$openid."&uname=".$uname."&uface=".$uface."&province=".$province."&city=".$city."&sex=".$sex;
	}else{
		$url=$url."&u=".$u."&openid=".$openid."&uname=".$uname."&uface=".$uface."&province=".$province."&city=".$city."&sex=".$sex;
	}
	header("location:".$url);
	exit;
}